<template>
  <div class="page-wrap">
    <div class="page-header">
      <div class="page-title">
        出入库明细
        <el-tag type="info" effect="plain" class="title-tag">Inbound/Outbound Details</el-tag>
      </div>
      <div class="page-actions">
        <el-button @click="goBack" plain>返回</el-button>
      </div>
    </div>

    <el-card class="search-card" shadow="never">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="产品名称">{{ productName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="记录数">{{ total }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" border stripe height="520" :header-cell-style="{background:'#f7f9fc'}">
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="productNumber" label="产品编号" min-width="120" />
        <el-table-column prop="specification" label="规格型号" min-width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="warehouseName" label="仓库" min-width="120" />
        <el-table-column prop="warehouseAreaName" label="库区" min-width="120" />
        <el-table-column prop="binLocationName" label="库位" min-width="120" />
        <el-table-column prop="transactionType" label="类型" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="100" align="right">
          <template #default="{ row }">{{ formatNumber(row.unitPrice) }}</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="110" align="right">
          <template #default="{ row }">{{ formatNumber(row.quantity) }}</template>
        </el-table-column>
        <el-table-column prop="transactionTime" label="时间" min-width="160">
          <template #default="{ row }">{{ formatTime(row.transactionTime) }}</template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100" />
        <el-table-column prop="remarks" label="备注" min-width="160" />
      </el-table>

      <div class="pager">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="query.pageindex"
          :page-size="query.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ReadClients } from '../../Urls/AxiosHelper'

const Read = ReadClients[0]
const route = useRoute()
const router = useRouter()

const productName = ref<string>((route.query.productName as string) || '')

interface InventoryTransactionItem {
  id: number
  productName: string
  productNumber: string
  specification: string
  unit: string
  warehouseName: string
  warehouseAreaName?: string
  binLocationName?: string
  transactionType: string
  quantity: number
  unitPrice: number
  transactionTime: string
  applicant?: string
  remarks?: string
}

interface ApiResponse<T> {
  code: number
  message: string
  data: {
    totalCount: number
    totalPage: number
    data: T[]
  }
}

const loading = ref(false)
const tableData = ref<InventoryTransactionItem[]>([])
const total = ref(0)

const query = reactive({
  pageindex: 1,
  pagesize: 10,
})

async function fetchList(){
  if(!productName.value){
    ElMessage.warning('未提供产品名称，无法查询明细')
    return
  }
  loading.value = true
  try{
    const res = await Read.get<ApiResponse<InventoryTransactionItem>>('/wareread/api/ReportSummary/InventoryTransactions',{
      params:{
        pageindex: query.pageindex,
        pagesize: query.pagesize,
        ProductName: productName.value,
      }
    })
    const payload = res.data
    if(payload.code !== 200){
      throw new Error(payload.message || '请求失败')
    }
    tableData.value = payload.data?.data || []
    total.value = payload.data?.totalCount || 0
  }catch(err:any){
    ElMessage.error(err?.message || '加载失败')
  }finally{
    loading.value = false
  }
}

function handleCurrentChange(page:number){
  query.pageindex = page
  fetchList()
}

function handleSizeChange(size:number){
  query.pagesize = size
  query.pageindex = 1
  fetchList()
}

function formatNumber(n: number | string){
  const num = Number(n ?? 0)
  return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 2 }).format(num)
}

function formatTime(value?: string){
  if(!value) return '-'
  const d = new Date(value)
  if(Number.isNaN(d.getTime())) return String(value)
  return new Intl.DateTimeFormat('zh-CN', { year:'numeric', month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit', second:'2-digit' }).format(d)
}

function goBack(){
  router.back()
}

watch(() => route.query.productName, (nv) => {
  productName.value = (nv as string) || ''
  query.pageindex = 1
  fetchList()
})

onMounted(fetchList)
</script>

<style scoped>
.page-wrap{
  display:flex;
  flex-direction:column;
  gap:12px;
}
.page-header{ display:flex; align-items:center; justify-content:space-between; }
.page-title{ font-size:18px; font-weight:600; display:flex; align-items:center; gap:8px; }
.title-tag{ vertical-align: middle; }
.page-actions{ display:flex; gap:8px; }
.pager{ display:flex; justify-content:flex-end; margin-top:12px; }
</style>
